import {
	getUserInfo
} from '../api/api.js'
import {
	showTishi
} from '../index.js'
import {
	API_URL,
	BASE_URL
} from '@/common/public_url.js'
import { setType } from '../format/format.js'


export function handleLogin(auth, code) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: API_URL + "/v0.1/account/login_app/",
			timeout: 10000,
			type: 'GET',
			data: {
				mode: code?'code':'',
				source: 'app',
			},
			responseType:'text',
			header: {
				"Authorization": "Basic " + auth,
			},
			success: function(res) {
				if (res.statusCode === 200) {
					// console.log(res,'登录')
					uni.setStorageSync('JWTtoken', res.data.token)
					if (res.data.status === 0) {
						//保存请求头
						uni.setStorageSync("headerapp", auth);
						uni.setStorageSync('csftokenheaderapp', res.header.rspcsftoken);
						uni.setStorageSync('sessionidheaderapp', res.header.rspsessionid);
					
						getUserInfo().then(res => {
							// console.log(res)
							if (res.status === 0) {
								showTishi('登录成功')
								uni.setStorageSync("vehicles", JSON.stringify(res.vehicles))
								uni.setStorageSync("userInfo", JSON.stringify(res))
								uni.setStorageSync("yc_coupon", JSON.stringify(res.yc_coupon))
								setTimeout(() => {
									// #ifdef APP-PLUS || MP-WEIXIN
									uni.switchTab({
										url: '/pages/index/app-home',
										fail:function(error){
											console.log(error,'为什么不跳转')
										}
									})
									// #endif
									
									// #ifdef H5
									if(setType() == 'wxFlag'){
										window.location.href = pageList.home
									}else{
										uni.navigateTo({
											url: '/pages/index/h5-home'
										})
									}
									// #endif
								}, 200)
							}else {
								showTishi(res.detail)
							}
						})
					} else {
						if (res.data.status == 20009) {
							showTishi('密码错误')
						} else if (res.data.status == 20011) {
							showTishi('用户不存在')
						} else if (res.data.status === 70001) {
							showTishi('仅限于app用户')
						} else {
							if(res.data.msg){
								showTishi(res.data.msg)
							}else if(res.data.detail){
								showTishi(res.data.detail)
							}else{
								uni.showToast({
									title: "状态码：" + res.data.status,
									icon: 'none'
								})
							}
						}
					}
				} else {
					showTishi(res.errMsg)
				}
			},
			fail: function(error) {
				showTishi(error)
				reject(error)
			},
			complete: function(res) {
				console.log(res,"complete")
			},
		})
	})
}

export function wxLogin(){
	wx.login({
		success:function(res){
			if(res.code){
				// handleLogin(res.code, true)
			}
			console.log('登录成功',res)
		},
		fail:function(res){
			console.log('登录失败',res)
		},
		complete:function(res){
			console.log('登录完成',res)
		}
	})
	
	wx.getUserInfo({
		success:function(res){
			console.log('获取用户信息成功',res)
		},
		fail:function(res){
			console.log('获取用户信息失败',res)
		},
		complete:function(res){
			console.log('获取用户信息完成',res)
		}
	})
}

